package com.common.allCommon;

import java.io.File;
import java.io.FileFilter;
import java.util.Calendar;
import java.util.Locale;
import java.util.regex.Pattern;

import android.text.TextUtils;

/**
 * ClassName:EraseLog Function: 删除存储器上的日志
 * 
 * @author 林胜杰
 * @version
 * @since Ver 1.1
 * @Date 2013 2013-12-23 上午11:13:26
 * 
 * @see
 */
public class EraseLog {
	private static volatile EraseLog instance;

	private boolean mbRunning = false; // 是否运正在运行

	private String mstrSDCardCacheDir;
	private String mstrInternalCacheDir;

	public static final int LOG_FILE_NAME_LEN = 14; // 2013-12-19.log共14个字符

	public static EraseLog getInstance(String strSDCardCacheDir,
			String strInternalCacheDir) {
		if (instance == null) {
			synchronized (EraseLog.class) {
				if (instance == null) {
					instance = new EraseLog(strSDCardCacheDir,
							strInternalCacheDir);
				}
			}
		}
		return instance;
	}

	private EraseLog(String strSDCardCacheDir, String strInternalCacheDir) {
		mstrSDCardCacheDir = new String(strSDCardCacheDir);
		mstrInternalCacheDir = new String(strInternalCacheDir);
	}

	public void EraseLogIfNotRunning() {
		if (!mbRunning) {
			mbRunning = true;
			eraseLogOneMonthAgo();
			mbRunning = false;
		}
	}

	// 删除一个月前的日志
	private void eraseLogOneMonthAgo() {
		final String LOG_NAME = "Log";
		StringBuilder sbDir = new StringBuilder();

		// 先删SD卡
		if (!TextUtils.isEmpty(mstrSDCardCacheDir)) {
			eraseLogs(sbDir.append(mstrSDCardCacheDir).append(LOG_NAME)
					.append(File.separator).toString());
		}

		// 清空
		sbDir.delete(0, sbDir.length());

		// 再删内部存储器
		if (!TextUtils.isEmpty(mstrInternalCacheDir)) {
			eraseLogs(sbDir.append(mstrInternalCacheDir).append(LOG_NAME)
					.append(File.separator).toString());
		}
	}

	// 删除指定路径下的日志
	private void eraseLogs(String strDir) {
		File fDir = new File(strDir);

		// 计算当前日期减一周的整数值：20131219 --> 20131212 e.g.
		Calendar calendarCur = Calendar.getInstance();
		calendarCur.add(Calendar.DAY_OF_MONTH, -7);
		final int iCriticalDate = calendarCur.get(Calendar.YEAR) * 10000
				+ (calendarCur.get(Calendar.MONTH) + 1) * 100
				+ calendarCur.get(Calendar.DAY_OF_MONTH);

		// 取得所有一个月前的日志
		File[] dirs = fDir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				String strLogName = pathname.getName().toLowerCase(
						Locale.getDefault());
				if (strLogName.length() == LOG_FILE_NAME_LEN
						&& strLogName.endsWith(".log")) {
					Pattern pattern = Pattern
							.compile("\\d{4}-\\d{2}-\\d{2}.log");
					if (pattern.matcher(strLogName).matches()) {
						strLogName = strLogName.substring(0, 10).replace("-",
								"");
						try {
							int iDateOfLog = Integer.parseInt(strLogName);
							if (iDateOfLog <= iCriticalDate) {
								return true;
							}
						} catch (NumberFormatException e) {
							return false;
						}
					}
					return false;
				}

				return false;
			}
		});

		if (null != dirs) {
			for (File file : dirs) {
				file.delete();
			}
		}
	}

}
